<template>
    <div class="jianzhan-content">
        <Crumb :name="name + $t('stockIn.stockIn')"/>
        <div class="content">
            <el-button size="small" @click="openAdd" type="primary" v-if="urlAvailible('stockIn-operate')">
                {{$t('stockIn.addStockIn')}}
            </el-button>
            <el-button size="small" @click="download" type="primary">{{$t('download')}}</el-button>

            <Search>
                <el-input v-model="key"
                          class="input"
                          size="small"
                          prefix-icon="el-icon-search"
                          @input="keyChange"
                          :placeholder="$t('stockIn.search')"></el-input>
                <el-select v-model="key1"
                           class="input"
                           size="small"
                           prefix-icon="el-icon-search"
                           filterable
                           clearable
                           :placeholder="$t('stockIn.search1')">
                    <el-option v-for="item in shipList" :key="item" :value="item" :label="item"></el-option>
                </el-select>

                <el-date-picker v-model="date"
                                type="month"
                                :placeholder="$t('stockIn.month')"
                                size="small"
                                value-format="yyyy-MM"></el-date-picker>
                <el-button type="primary" icon="el-icon-search" size="small" @click="search">{{$t('search')}}</el-button>
                <el-button type="text" @click="showEdit = !showEdit" class="btn">{{btnText}}</el-button>

                <el-select collapse-tags multiple v-model="stockInShowColumn" style="margin-left: 20px;"
                           placeholder="Stock In Column"
                           size="small">
                    <el-option
                            label="Stock In No"
                            value="stockInNo">
                    </el-option>
                    <el-option
                            label="Exporter"
                            value="exporter">
                    </el-option>
                    <el-option
                            label="Ship Number"
                            value="shipNumber">
                    </el-option>
                </el-select>


            </Search>
            <div class="table-wrapper">
                <el-table border
                          stripe
                          row-key="id"
                          :cell-style="rowClass"
                          @filter-change="filterChange"
                          @expand-change="getPartDetail"
                          :data="stockList"
                >
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-table :data="props.row.partList" border show-summary>
                                <el-table-column
                                        prop="partsNumber"
                                        :label="$t('part.partNo')"
                                        width="180">
                                </el-table-column>
                                <el-table-column
                                        prop="denomination"
                                        :label="$t('part.description')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="designation"
                                        :label="$t('part.description')"
                                >
                                </el-table-column>
                                <el-table-column
                                        prop="partsQuantity"
                                        :label="$t('part.qty')"
                                >
                                </el-table-column>

                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('stockIn.stockInNo')" prop="stockInNum"
                                     v-if="stockInShowColumn.indexOf('stockInNo') > -1"></el-table-column>
                    <el-table-column :label="$t('exporter')" prop="exporterDesc"
                                     v-if="tid!=='IEC' && (stockInShowColumn.indexOf('exporter') > -1)"></el-table-column>
                    <el-table-column :label="$t('stockIn.shipNumber')" prop="shipNumber"
                                     v-if="stockInShowColumn.indexOf('shipNumber') > -1"></el-table-column>
                    <el-table-column :label="$t('stockIn.stockInDate')" sortable
                                     prop="stockInDateStr"></el-table-column>
                    <el-table-column :label="$t('stockIn.releaseDate')" sortable prop="releaseDate"></el-table-column>
                    <el-table-column :label="$t('stockIn.type')"
                                     prop="exploitDesc"
                                         column-key="exploit"
                                     :filters="[
                                         {text:'Restock In',value:2},
                                         {text:'Self Purchase',value:1},
                                         {text:'Consignment',value:0}
                                     ]"
                    ></el-table-column>
                    <el-table-column
                            label="Status"
                            column-key="timeOutStatus"
                            prop="timeOutStatus"
                            :filters="[{text:'Unstock',value:1},{text:'Stock',value:0},{text:'No Status ',value:9},{text:'No Release',value:2}]"
                    >
                        <template slot-scope="scope">
                            <span>{{getStatus(scope.row.timeOutStatus)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="Detail" v-if="showEdit">
                        <template slot-scope="stock">
                            <el-button type="primary" v-if="urlAvailible('stockIn-operate')" size="small"
                                       @click="showDetail(stock.row)">{{$t('detail')}}
                            </el-button>
                            <el-button type="danger" v-if="urlAvailible('stockin-delete')" size="small"
                                       @click="deleteStockIn(stock.row.id)">{{$t('delete')}}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>
        <el-dialog :title="$t('stockIn.stockInOrder')" :visible.sync="dialogVisible" width="80%">
            <!--点击IEL进入时-->
            <el-form :model="stock" ref="stock" :rules="rule" label-width="150px" v-if="tid===''">
                <div class="flex">
                    <div class="flex-content">
                        <el-form-item :label="$t('stockIn.usage')" prop="exploit">
                            <el-select v-model="stock.exploit" size="small" class="input">
                                <el-option :label="$t('consignment')" :value=0></el-option>
                                <el-option :label="$t('self')" :value=1></el-option>
                                <el-option :label="$t('restockIn')" :value=2></el-option>
                            </el-select>
                        </el-form-item>
                        <div v-if="stock.exploit === 2">
                            <el-form-item :label="$t('stockOut.stockOutDate')">
                                <el-date-picker v-model="stock.stockOutDate" value-format="yyyy-MM-dd" type="date"
                                                :placeholder="$t('stockOut.stockOutDate')"
                                                @change="getStockOutSelectList"></el-date-picker>
                            </el-form-item>
                            <el-form-item :label="$t('stockOut.stockOutNo')">
                                <el-select v-model="stock.stockOutId" size="small" class="input"
                                           @change="getStockOutDetail">
                                    <el-option v-for="item in stockoutList" :key="item.stockOutId"
                                               :label="item.stockOutNumber" :value="item.stockOutId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <div v-else>
                            <el-form-item :label="$t('export.exportNo')" prop="exportNum">
                                <el-input v-model="stock.exportNum" size="small" class="input"></el-input>
                            </el-form-item>
                        </div>
                        <el-form-item :label="$t('stockIn.stockInDate')" prop="stockInDateStr">
                            <el-date-picker v-model="stock.stockInDateStr" value-format="yyyy-MM-dd" size="small"
                                            class="input"/>
                        </el-form-item>
                        <el-form-item :label="$t('warehouse')" v-if="stock.exploit !== 2" prop="warehouse">
                            <el-select v-model="stock.warehouse"
                                       :placeholder="$t('warehouse')"
                                       size="small"
                                       class="input">
                                <el-option
                                        v-for="item in warehouseList"
                                        :key="item.id"
                                        :label="item.warehouseName"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="flex-content" v-if="stock.exploit === 2">
                        <el-form-item :label="$t('stockIn.stockInNo')">
                            <el-input v-model="stockinNum" disabled size="small" class="input"/>
                        </el-form-item>
                    </div>
                    <div class="flex-content" v-else>
                        <el-form-item :label="$t('exporter')" prop="exporter">
                            <el-select v-model="stock.exporter" size="small" class="input" placeholder="Exporter">
                                <el-option label="Inline" :value=0></el-option>
                                <el-option label="Shacman" :value=1></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('stockIn.shipNumber')">
                            <el-input v-model="shipNumber1" :placeholder="$t('stockIn.shipNumber')" size="small"
                                      style="width: 40%"></el-input>
                            <el-input v-model="shipNumber2" :placeholder="$t('stockIn.shipNumber')" size="small"
                                      style="width: 20%"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('stockIn.stockInNo')">
                            <el-input v-model="stockinNum" disabled size="small" class="input"/>
                        </el-form-item>
                        <el-form-item :label="$t('stockIn.boxNo')" prop="totalBoxes">
                            <el-input v-model="stock.totalBoxes" :placeholder="$t('stockIn.boxNo')" size="small"
                                      class="input"></el-input>
                        </el-form-item>

                    </div>
                </div>
                <div style="text-align: left;margin-bottom: 10px;" v-show="stock.exploit !== 2">
                    <el-button size="small" type="primary" @click="dbVisible = true">Add Parts</el-button>
                    <label class="label" for="partExcel">Upload Excel</label>
                    <input type="file" id="partExcel" ref="file"
                           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                           size="small" @change="fileChange" style="display: none"/>
                </div>
                <Data-Base @deleteItem="deleteItem" :partList="partList" :show-o-qty="true" />
            </el-form>
            <!--点击IEC进入时-->
            <el-form :model="stock" ref="stock" :rules="rule" label-width="150px" v-else>
                <div class="flex">
                    <div class="flex-content">
                        <el-form-item :label="$t('stockIn.usage')" prop="exploit">
                            <el-select v-model="stock.exploit" size="small" class="input">
                                <el-option :label="$t('consignment')" :value=0></el-option>
                                <el-option :label="$t('import')" :value=1></el-option>
                                <el-option :label="$t('local')" :value=3></el-option>
                                <el-option :label="$t('restockIn')" :value=2></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('servicePurchase.purchaseNo')"
                        >
                            <el-select v-model="stock.exportId"
                                       @change="changePo"
                                       :placeholder="$t('servicePurchase.purchaseNo')"
                                       size="small"
                                       class="input">
                                <el-option
                                        v-for="item in poList"
                                        :disabled="!!item.selectOrNot"
                                        :key="item.id"
                                        :value="item.id"
                                        :label="item.purchaseNumber"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="supplier" :label="$t('supplier')" v-show="stock.exploit === 3">
                            <el-select clearable v-model="stock.supplier" :placeholder="$t('supplier')" size="small"
                                       class="input">
                                <el-option
                                        v-for="item in supplierList"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <div v-if="stock.exploit === 2">
                            <el-form-item :label="$t('stockOut.stockOutDate')" prop="stockOutDate">
                                <el-date-picker v-model="stock.stockOutDate" value-format="yyyy-MM-dd" type="date"
                                                placeholder="Stock Out Time"
                                                @change="getStockOutSelectList"></el-date-picker>
                            </el-form-item>
                            <el-form-item :label="$t('stockOut.stockOutNo')">
                                <el-select v-model="stock.stockOutId" size="small" class="input"
                                           @change="getStockOutDetail">
                                    <el-option v-for="item in stockoutList" :key="item.stockOutId"
                                               :label="item.stockOutNumber" :value="item.stockOutId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <el-form-item :label="$t('stockIn.stockInDate')" prop="stockInDateStr">
                            <el-date-picker v-model="stock.stockInDateStr" value-format="yyyy-MM-dd" size="small"
                                            class="input"/>
                        </el-form-item>
                        <el-form-item :label="$t('warehouse')" prop="warehouse">
                            <el-input v-model="stock.warehouse"
                                      disabled placeholder="warehouse-3" size="small"
                                      class="input"/>
                        </el-form-item>
                    </div>
                    <div class="flex-content" v-if="stock.exploit === 2">
                        <el-form-item :label="$t('stockIn.stockInNo')">
                            <el-input v-model="stockinNum" disabled size="small" class="input"></el-input>
                        </el-form-item>
                    </div>
                    <div class="flex-content" v-else v-show="stock.exploit!==0">
                        <el-form-item :label="$t('stockIn.shipNumber')" v-show="stock.exploit!==3">
                            <el-select v-model="stock.shipNumber" size="small" class="input">
                                <el-option v-for="item in shipList" :key="item" :label="item"
                                           :value="item">
                                </el-option>
                            </el-select>

                        </el-form-item>
                        <el-form-item :label="$t('stockIn.stockInNo')">
                            <el-input v-model="stockinNum" disabled size="small" class="input"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('stockIn.boxNo')" prop="totalBoxes" v-show="stock.exploit!==3">
                            <el-input v-model="stock.totalBoxes" placeholder="Box Number" size="small"
                                      class="input"></el-input>
                        </el-form-item>
                    </div>
                </div>

                <Data-Base @deleteItem="deleteItem" :stockOutNo="stock.stockOutNo" :partList="partList"
                           :show-o-qty="true"/>
            </el-form>

            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
                        <el-button @click="saveForm"
                                   v-if="(!(stock.saveOrConfirm === 1)) && urlAvailible('stockIn-operate') "
                                   type="warning">{{$t('save')}}</el-button>
                        <el-button type="primary"
                                   v-if="(!(stock.saveOrConfirm === 1)) && urlAvailible('stockIn-operate')"
                                   @click="submitForm">{{$t('confirm')}}</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="New part"
                :visible.sync="notExistVisible"
                width="90%"
        >
            <el-table
                    :data="notExist"
                    border
                    stripe
                    style="width: 100%">
                <el-table-column
                        type="index"
                        label="No"
                >
                </el-table-column>
                <el-table-column
                        prop="partsNum"
                        label="part number"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="denomination"
                        label="description"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="designation"
                        label="description">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="notExistVisible = false">Confirm</el-button>
            <el-button @click="insertDataBase">Insert Into Data Base</el-button>
          </span>
        </el-dialog>
        <el-dialog
                title="Progress"
                :visible="progress"
                width="50%"
        >
            <span>{{current}}／{{notExist.length}}</span>
            <el-progress :percentage="(current/notExist.length)*100"/>
        </el-dialog>
        <el-dialog
                :title="$t('download')"
                :visible.sync="dialogVisible1"
                width="50%"
                >
            <div>
                <el-date-picker v-model="startTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
            </div>
            <div>
                <el-date-picker v-model="endTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dwn">{{$t('download')}}</el-button>
          </span>
        </el-dialog>
        <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible" :show-all="true"/>
    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import Search from '../../components/common/search'
    import PartItem from '../../components/part/sparePartItem'
    import DataBase from '../../components/part/spDateBase_warehouse'
    import {
        getStockInList,
        stockIn,
        getStockInDetail,
        saveStockIn,
        getStockInRecord,
        deleteStockIn,
        getStockoutSelectList,
        getStockOutDetail,
        getStockOutNo,
        showAllExport,
        getAllShipInfo,
        getPoDetail,
        getPoList
    } from "../../api/service";
    import {getWarehouseList} from "../../api/warehouse";
    import {addPart} from "../../api";
    import {mapMutations} from 'vuex'
    import {upLoadFile} from "../../api";
    import {mapActions} from 'vuex';
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import spMixins from '../../util/spMixins'
    import authMixins from '../../util/authMixins'
    import {baseURL,throttle} from "../../util";
    import {getVendorList} from "../../api/jianzhan";

    export default {
        name: "stock-out",
        mixins: [mixins, spMixins, authMixins],
        props: {
            belongModule: {
                type: Number,
                default: 1
            },
            name: {
                type: String,
                default: ''
            },
            tid: {  //通过iec进入参数判断
                type: String,
                default: ''
            }
        },
        data() {
            return {
                startTime:'',
                endTime:'',
                exploit: '',
                timeOutStatus: '',
                date: '',
                showEdit: false,
                shipNumber1: '',
                shipNumber2: '',
                list: [],
                workNoList: [],
                notExist: [],
                stockInShowColumn: [
                    "stockInNo",
                    "exporter",
                    "shipNumber"
                ],
                poList: [],
                rule: {
                    stockInDateStr: [{required: true}],
                    exploit: [{required: true}],
                    exporter: [{required: true}],
                    shipNumber: [{required: true}],
                    totalBoxes: [{required: true}],
                },
                stockoutList: [],
                supplier: [{required: true}],
                warehouseList: [],
                stock: {
                    stockInNum: '',
                    stockOutDate: '',
                    stockInDateStr: '',
                    stockOutNum: '',
                    stockOutId: '',
                    stockOutDetails: [],
                    exploit: 0,
                    supplier: '',
                    supplierName: '',
                    exporter: '',
                    exportId: '',
                    exportNum: '',
                    stockOutNo: '',
                    warehouse: 3,
                    shipNumber: '',
                    totalBoxes: ''
                },
                key: '',
                key1: '',
                dialogVisible: false,
                dialogVisible1: false,
                notExistVisible: false,
                current: 0,
                progress: false,
                editable: true,
                supplierList: [], // 供应商
                supplierId: [],  //   供应商id
                stockOutNoList: [],//  出库单号
                detailList: [],
                // supplier:[],
                shipList: [], // 船的信息
            }
        },
        computed: {
            btnText() {
                return this.showEdit ? 'Complete' : this.$t('edit')
            },
            stockList() {
                return this.list
            },
            stockinNum() {
                let {totalBoxes, exportId, stockOutNum, stockOutId, exportNum,exploit,stockInNum} = this.stock;
                // if(stockInNum) {
                //     return stockInNum
                // }
                const target = this.detailList.find(item => item.id === stockOutId);
                const po = this.poList.find(item => item.id === exportId);
                let purchaseNumber;
                if (po) {
                    purchaseNumber = po.purchaseNumber
                }
                if (target) {
                    stockOutNum = target.stockOutNum;
                    return stockOutNum;
                }
                    if(exploit === 2) {
                        return stockOutNum + '_R'
                    }
                return `${purchaseNumber || stockOutNum || exportNum}/${totalBoxes}`
            }
        },
        created() {
            this._getStockInList();
            this.getWarehouseList();
            // this.getStockOutNo();
            this.getAllShipInfo();
            this.getPoList()
        },
        methods: {
            keyChange(){
               throttle(this.search,500)();
            },
            getStatus(status){
                switch (status){
                    case 0:
                     return 'Stock';
                    case 1:
                        return 'Unstock';
                    case 2:
                        return "No Release";
                    case 9:
                        return "No Status"
                }
            },
            filterChange(filter) {
                Object.keys(filter).forEach((key) => {
                    this[key] = filter[key][0]
                });
                this.search()
            },
            changePage(page){
                this.pageNum = page;
                this._getStockInList()
            },
            search() {
                this.pageNum = 1;
                this._getStockInList()
            },
            async changePo(value) {
                const {data, status, msg} = await getPoDetail(value);
                if (status === ERROR_OK) {
                    this.partList = data.iecPurchaseDetailList.map(item => {
                        return {
                            ...item,
                            id: item.partsId,
                            salesPrice: item.purchasePriceChn || item.purchasePriceIdr,
                            number: item.partsQuantity,
                            oQty: item.oQty
                        }
                    });
                } else {
                    this.$message.error(msg);
                }
            },
            async getPoList() {
                const {status, data} = await getPoList();
                if (status === ERROR_OK) {
                    this.poList = data;
                }
            },
            async getPoDetail(id) {
                const {status, data} = await getPoDetail(id);
                if (status === ERROR_OK) {
                    this.partList = data.iecPurchaseDetailList
                }
            },
            async getAllShipInfo() {
                const {status, data} = await getAllShipInfo()
                if (status === ERROR_OK) {
                    this.shipList = data
                }
            },
            rowClass({row}) {
                if (row.timeOutStatus) {
                    return {
                        background: "#c60023 50%",
                        color: 'white'
                    }
                }
            },
            dwn(){
                window.open(baseURL + '/statistical_report/export_excel_stock_in.file?warehouse=&belongModule=' + this.belongModule + '&startTime=' + this.startTime + '&endTime=' + this.endTime)
            },
            download() {
                this.dialogVisible1 = true
            },
            filterHandler(value, row, column) {
                const property = column['property'];
                return row[property] === value;
            },
            async getStockOutDetail(v) {
                const {data, status} = await getStockOutDetail(v);
                const target = this.stockoutList.find(item => {
                    return item.stockOutId === v
                });
                if (target) {
                    this.$set(this.stock, 'stockOutNum', target.stockOutNumber)
                }
                if (status === ERROR_OK) {
                    this.partList = data.map(part => {
                        return {
                            ...part.spareParts,
                            detailWarehouse:part.detailWarehouse,
                            applyQuantity:part.applyQuantity,
                            number: part.partsQuantity,
                            oQty: part.oQty
                        }
                    })
                }
            },
            async getStockOutSelectList(v) {
                const {status, data, msg} = await getStockoutSelectList(this.belongModule, v);
                if (status === ERROR_OK) {
                    this.stockoutList = data;
                    this.$set(this.stock, 'stockOutNum', '')
                } else {
                    this.$notify.error(msg)
                }
            },
            async deleteStockIn(id) {
                if (window.confirm('delete ?')) {
                    const {status} = await deleteStockIn(id);
                    if (status === ERROR_OK) {
                        alert('deleted');
                        this._getStockInList()
                    }
                }
            },
            async getWarehouseList() {
                const {status, data} = await getWarehouseList();
                if (status === ERROR_OK) {
                    this.warehouseList = data
                }
            },
            async getPartDetail(r) {
                if (r.partList) {
                    return
                }
                const {status, data} = await getStockInRecord(r.id);
                if (status === ERROR_OK) {
                    r.partList = data;
                    const index = this.list.findIndex(item => item.id === r.id);
                    this.list.splice(index, 1, r);
                }

            },
            // 获取供应商接口
            async showSupplier() {
                if (this.stock.exploit === 3 && !this.supplierList.length) {
                    const {status, data} = await getVendorList(this.belongModule);
                    if (status === ERROR_OK) {
                        this.supplierList = data.map(item => {
                            return {id: item.id, value: item.chineseName}
                        })
                    }
                }
                //  获取船的信息
                if (this.stock.exploit === 1 && !this.shipList.length) {
                    const {status, data} = await showAllExport()
                    if (status === ERROR_OK) {
                        this.shipList = data
                    }
                }
            },
            //  获取出库单号
            async getStockOutNo() {
                const {status, data} = await getStockOutNo();
                if (status === ERROR_OK) {
                    this.detailList = data;
                    this.stockOutNoList = data.map(item => item.stockOutNum);
                }
            },
            //  自动显示时间  显示信息
            showDate() {
                const stockOutDetailList = this.detailList.find(item => item.id === this.stock.stockOutId);
                this.stock.stockInDateStr = stockOutDetailList.stockOutDateStr;
                this.partList = stockOutDetailList.stockOutDetailList ? stockOutDetailList.stockOutDetailList.map(part => {
                    return {
                        ...part.spareParts,
                        number: part.partsQuantity,
                        oQty: part.oQty
                    }
                }) : [];
            },
            //   confirm
            async submitForm() {
                const {stockInDateStr,
                    id,
                    exploit,
                    exporter,
                    exportId,
                    shipNumber,
                    totalBoxes,
                    stockOutId,
                    stockOutDate,
                    supplier,
                    exportNum} = this.stock;
                const stockInNum = this.stockinNum;
                const belongModule = this.belongModule;
                let stockInDetails = this.partList.map(item => {
                    return {
                        partsId: item.id || item.partsId,
                        partsQuantity: item.number,
                        oQty: item.oQty,
                        detailWarehouse:item.detailWarehouse
                    }
                });
                stockInDetails = JSON.stringify(stockInDetails);
                const {status, msg} = await stockIn({
                    supplier,
                    stockOutId,
                    stockOutDate,
                    belongModule,
                    stockInNum,
                    stockInDateStr,
                    id,
                    exportNum,
                    stockInDetails,
                    exploit,
                    exporter,
                    exportId,
                    shipNumber,
                    totalBoxes,
                    shipA: this.shipNumber1,
                    shipB: this.shipNumber2,
                    warehouse: this.tid === "IEC" ? 3 : this.stock.warehouse
                });
                if (status === ERROR_OK) {
                    this.clear();
                    stockInDetails = JSON.parse(stockInDetails).map(item => {
                        return {
                            partsId: item.partsId,
                            partsQuantity: -item.partsQuantity,
                            oQty: item.oQty
                        }
                    });
                    this.modPartNum(stockInDetails);
                    this._getStockInList();
                    this.dialogVisible = false;
                    this.$notify.success('Stock in Successfully')
                } else {
                    this.$notify.error(msg)
                }
            },
            async saveForm() {
                const {
                    stockInDateStr,
                    id,
                    exploit,
                    exportNum,
                    exporter,
                    exportId,
                    shipNumber,
                    totalBoxes,
                    stockOutId,
                    stockOutDate,
                    supplier,
                } = this.stock;
                const stockInNum = this.stockinNum;
                const belongModule = this.belongModule;
                let stockInDetails = this.partList.map(item => {
                    return {
                        partsId: item.id || item.partsId,
                        partsQuantity: item.number,
                        oQty: item.oQty,
                        detailWarehouse:item.detailWarehouse
                    }
                });
                stockInDetails = JSON.stringify(stockInDetails);
                const {status, msg} = await saveStockIn({
                    supplier,
                    stockOutId,
                    stockOutDate,
                    belongModule,
                    stockInNum,
                    exportNum,
                    stockInDateStr,
                    id,
                    stockInDetails,
                    exploit,
                    exporter,
                    exportId,
                    shipNumber,
                    totalBoxes,
                    shipA: this.shipNumber1,
                    shipB: this.shipNumber2,
                    warehouse: this.tid === "IEC" ? 3 : this.stock.warehouse
                });
                if (status === ERROR_OK) {
                    this.clear();
                    this.stockInDetails = JSON.parse(stockInDetails).map(item => {
                        return {
                            partsId: item.partsId,
                            partsQuantity: -item.partsQuantity,
                            oQty: item.oQty,
                        }
                    });
                    this._getStockInList();
                    this.dialogVisible = false;
                    this.$notify.success('Save Successfully')
                } else {
                    this.$notify.error(msg)
                }
                // }
                // })

            },
            async fileChange(e) {
                const files = e.target.files;
                const file = files[0];
                if (file) {
                    let formData = new FormData();
                    formData.append('exFiles', file);
                    const {status, data, msg} = await upLoadFile(formData);
                    if (status === ERROR_OK) {
                        if (data.data.notExistSparePartsDataBase.length) {
                            this.notExistVisible = true;
                            this.notExist = data.data.notExistSparePartsDataBase
                        }
                        this.partList = data.data.stockInDetail.map(part => {
                            return {
                                ...part.spareParts,
                                number: part.partsQuantity
                            }
                        })
                    } else {
                        this.$notify.error(msg)
                    }
                }
                this.$nextTick(() => {
                    this.$refs.file.value = ''
                })
            },
            async showDetail(stock) {

                this.dialogVisible = true;
                this.editable = false;
                const {status, data} = await getStockInDetail(stock.id);
                if (status === ERROR_OK) {
                    this.shipNumber1 = data.shipA;
                    this.shipNumber2 = data.shipB;
                    this.stock.saveOrConfirm = data.saveOrConfirm;
                    this.stock.id = data.id;
                    this.stock.stockInNum = data.stockInNum;
                    this.stock.stockInDateStr = data.stockInDateStr;
                    this.stock.stockOutId = data.stockOutId;
                    this.stock.exportNum = data.exportNum;
                    this.stock.exploit = data.exploit;
                    this.stock.exporter = data.exporter;
                    this.stock.exportId = data.exportId;
                    if (this.tid === 'IEC') {
                        this.stock.warehouse = 'Warehouse-3';
                    } else {
                        this.stock.warehouse = data.warehouse;
                    }
                    this.stock.shipNumber = data.shipNumber;
                    this.stock.supplier = data.supplier ? data.supplier : '';
                    this.stock.totalBoxes = data.totalBoxes;
                    const list = data.stockInDetailList || [];
                    this.partList = list.map(part => {
                        return {
                            ...part.spareParts,
                            number: part.partsQuantity,
                            oQty: part.oQty,
                            detailWarehouse:part.detailWarehouse
                        }
                    })
                    const {status: status1, data: data1} = await getStockoutSelectList(this.belongModule, stock.stockOutDate);
                    if (status1 === ERROR_OK) {
                        this.stockoutList = data1;
                        const target = data1.find(item => {
                            return item.stockOutId === stock.stockOutId
                        });
                        if (target) {
                            this.$set(this.stock, 'stockOutNum', target.stockOutNumber)
                        }
                        this.stock.stockOutDate = data1.stockOutDate

                    }
                }
            },
            async _getStockInList() {
                const date = this.date || '';
                console.log(date);
                let stockMonth = undefined;
                let stockYear = undefined;
                if (date) {
                    stockMonth = date.split('-')[1];
                    stockYear = date.split('-')[0];
                }
                const {status, data} = await getStockInList({
                    stockYear,
                    stockMonth,
                    belongModule: this.belongModule,
                    pageNum: this.pageNum,
                    exploit: this.exploit,
                    timeOutStatus: this.timeOutStatus,
                    shipNumber: this.key1,
                    stockInNum: this.key
                });
                if (status === ERROR_OK) {

                    this.list = data.list;
                    this.total = data.total
                }
            },
            async insertDataBase() {
                this.progress = true;
                for (const item of this.notExist) {
                    const part = {
                        partsNumber: item.partsNum,
                        denomination: item.denomination,
                        designation: item.designation
                    };
                    const {data, status} = await addPart(part);
                    if (status === ERROR_OK) {
                        part.id = data.id;
                        part.quantity = 0;
                        part.salePrice = 0;
                        this.addPart(part);
                        this.current = this.current + 1
                    }
                    if (this.current >= this.notExist.length) {
                        this.progress = false;
                        this.current = 0;
                        this.$notify.success('Insert into database successfully!')
                    }
                }
                this.progress = false
            },
            clear() {
                this.partList = [];
                this.shipNumber1 = '';
                this.shipNumber2 = '';
                this.stock = {
                    id: undefined,
                    stockOutId: undefined,
                    warehouse: '',
                    stockInNum: '',
                    stockOutNum: '',
                    stockInDateStr: '',
                    stockOutDate: '',
                    stockOutDetails: [],
                    exploit: 0,
                    exporter: '',
                    exportId: '',
                    shipNumber: '',
                    totalBoxes: ''
                };
                this.$nextTick(() => {
                    this.$refs.file.value = ''
                })
            },
            openAdd() {
                this.dialogVisible = true;
                this.clear()
            },
            ...mapActions(['modPartNum']),
            ...mapMutations(['addPart'])
        },
        watch: {
            date() {
                this._getStockInList();
            },
            shipNumber1(shipNumber) {
                const shipNumbers = shipNumber + '[' + this.shipNumber2 + ']';
                this.$set(this.stock, 'shipNumber', shipNumbers);
            },
            shipNumber2(shipNumber) {
                const shipNumbers = this.shipNumber1 + '[' + shipNumber + ']';
                this.$set(this.stock, 'shipNumber', shipNumbers);
            },
            "stock.exploit": {
                handler: function () {
                    this.showSupplier();
                    // this.getStockOutNo();
                },
                deep: true
            },
            "stock.warehouse":{
                handler:function (warehouse) {
                    if(warehouse) {
                        this.partList.forEach(item=>{
                            this.$set(item,'detailWarehouse',warehouse)
                        })
                    }
                }
            }
        },
        components: {
            Crumb, Search, PartItem, DataBase
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    td {
        transition: all 1s ease;
    }

    .btn {
        float: right;
        margin-right: 20px;
        transition: all 1s ease;
        opacity: 0.5;
        &:hover {
            opacity: 1;
        }
    }

    .label {
        width: 90px;
        height: 32px;
        line-height: 32px;
        border-radius: 3px;
        margin-left: 10px;
        text-align: center;
        cursor: pointer;
        font-size: 12px;
        background-color: #409eff;
        color: white;
        display: inline-block;
        vertical-align: top;
    }

    .flex {
        display: flex;
        .flex-content {
            flex: 1;
        }
    }

    .bg-red {
        background: #c60023;
        color: white;
    }

    .input {
        width: 50%;
    }
</style>